package com.example.harmonyosproject.server.service.impl;

import com.example.harmonyosproject.pojo.Favorite;
import com.example.harmonyosproject.pojo.News;
import com.example.harmonyosproject.server.mapper.NewsMapper;
import com.example.harmonyosproject.server.mapper.UserMapper;
import com.example.harmonyosproject.server.service.NewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class NewsServiceImpl implements NewsService {
    @Autowired
    NewsMapper newsMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public void addNews(News news) {
        String headImage =userMapper.getImage(news.getUserId());
        news.setHeadImage(headImage);
        newsMapper.addNews(news);
    }

    @Override
    public List<News> getAll(Integer id) {
        List<News> newsList= newsMapper.getAll(id);
        int i=0;
        for (News news:newsList){
            news.setUserName(userMapper.getName(news.getUserId()));
            news.setHeadImage(userMapper.getImage(news.getUserId()));
            Favorite favorite=newsMapper.isFavorite(new Favorite(id,news.getId()));
            if(favorite!=null){
                news.setFavorite(true);
                newsList.set(i,news);
            }
            i++;
        }
        return newsList;
    }

    @Override
    public List<News> getSelf(Integer id) {
        List<News> newsList= newsMapper.getSelf(id);
        int i=0;
        for (News news:newsList){
            news.setUserName(userMapper.getName(news.getUserId()));
            news.setHeadImage(userMapper.getImage(news.getUserId()));
            Favorite favorite=newsMapper.isFavorite(new Favorite(id,news.getId()));
            if(favorite!=null){
                news.setFavorite(true);
                newsList.set(i,news);
            }
            i++;
        }
        return newsList;
    }

    @Override
    public void addFavorite(Favorite favorite) {
        newsMapper.addFavorite(favorite);
    }

    @Override
    public List<News> getFavorite(Integer id) {
        List<News> newsList= newsMapper.getFavorite(id);
        for (News news:newsList) {
            news.setUserName(userMapper.getName(news.getUserId()));
            news.setHeadImage(userMapper.getImage(news.getUserId()));
        }
        return newsList;
    }

    @Override
    public void deleteFavorite(Favorite favorite) {
        newsMapper.deleteFavorite(favorite);
    }

    @Override
    public void addLike(Integer id) {
        newsMapper.updateLike(id);

    }
}
